<template>
  <u-popup
    v-model="selectValue"
    @close="onClose"
    mode="bottom"
    closeable
    :border-radius="30"
  >
    <view class="main">
      <view class="top-block">
        <view class="top-title">请选择所在地区</view>
        <!-- 已选区域tab -->
        <view class="u-border-bottom" v-if="selectValue">
          <u-tabs
            :list="tabList"
            @change="tabClick"
            :current="current"
            active-color="#2979ff"
          ></u-tabs>
        </view>
      </view>
      <!-- 区域选择 -->
      <view class="swiper-block">
        <swiper
          class="swiper"
          :disable-touch="true"
          :current="current"
          :indicator-dots="false"
          style="height: 100%"
          @change="swiperChange"
        >
          <swiper-item v-for="(type, idx) in areaList" :key="idx">
            <scroll-view
              scroll-y="true"
              class="swiper-list"
              :scroll-into-view="'i' + type.value + idx"
            >
              <view class="area-block">
                <view
                  class="area-item"
                  v-for="(item, index) in type.list"
                  :key="index"
                  :id="'i' + item.value + idx"
                  @click="onSelect(item, idx)"
                >
                  <view
                    class="name"
                    :style="{
                      color: type.value == item.value ? '#2979ff' : '',
                    }"
                  >
                    {{ item.name }}
                  </view>
                  <u-icon
                    v-if="type.value == item.value"
                    name="checkbox-mark"
                    color="#2979ff"
                    size="20"
                  ></u-icon>
                </view>
              </view>
            </scroll-view>
          </swiper-item>
        </swiper>
      </view>
      <view class="u-border-top" style="padding: 25rpx 20rpx">
        <u-button type="primary" @click="onConfirms">确定</u-button>
      </view>
    </view>
  </u-popup>
</template>

<script>
export default {
  name: "city-select",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    selectData: {
      type: Object,
      default: {},
    },
    manageType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      tabList: [
        {
          name: "请选择",
        },
      ],
      areaLength: 3, // 可选级数
      current: 0,
      selectValue: false,
      province: "",
      city: "",
      area: "",
      areaList: [
        { value: "", list: [] },
        { value: "", list: [] },
        { value: "", list: [] },
      ],
    };
  },
  watch: {
    value(newValue, oldValue) {  
      this.selectValue = newValue
    },
    selectValue(newValue, oldValue) {
      if(newValue == false ) {
        this.onClose()
      }
    },
    selectData(newVal) {
      if (newVal) {
        this.getSelectedArea();
      }
    },
  },
  computed: {},
  created() {},
  mounted() {
    // 新增地址，查询默认数据
    if (this.manageType != "edit") {
      this.onGetArea(0);
    }
  },
  methods: {
    swiperChange(e) {
      this.current = e.detail.current;
    },
    onConfirms() {
      this.selectValue = false;
      this.$emit("input", this.specShow);
      this.onConfirm();
    },
    // 确认选择
    onConfirm() {
      let obj = {
        name: "",
        province: this.areaList[0].value || "",
        city: this.areaList[1].value || "",
        area: this.areaList[2].value || "",
      };
      // 循环获取已选地区名称
      this.tabList.forEach((item, index) => {
        if (item.name != "请选择") {
          if (obj.name == "") {
            obj.name = item.name;
          } else {
            obj.name = obj.name + " " + item.name;
          }
        }
      });
      this.$emit("confirmSelect", obj);
    },
    // tab点击
    tabClick(val) {
      this.current = val;
    },
    // 关闭弹窗
    onClose() {
      this.selectValue = false;
      this.$emit("input", false);
      let wallIf = this.tabList.some((item) => {
        if (item.name == "请选择") {
          return true;
        }
      });
      // 未选完整地区默认返回原来的地址
      if (this.selectData.user_id && wallIf) {
        this.getSelectedArea();
      }
    },
    // 获取已选数据
    getSelectedArea() {
      // 微信小程序获取的地址，province city area 都为0 不默认赋值
      console.log("已选数据：", this.selectData);
      if (this.selectData.cityName == "选择") {
        this.areaList = [
          {
            value: "",
            list: [],
          },
          {
            value: "",
            list: [],
          },
          {
            value: "",
            list: [],
          },
        ];
        this.tabList = [
          {
            name: "请选择",
          },
        ];
        this.current = 0;
        this.onGetArea(0)
        return;
      }
      this.tabList = [
        {
          name: this.selectData.cityName.split(" ")[0] || '请选择',
        },
        {
          name: this.selectData.cityName.split(" ")[1] || '请选择',
        },
        {
          name: this.selectData.cityName.split(" ")[2] || '请选择',
        },
      ];
      this.areaList[0].value = this.selectData.province;
      this.areaList[1].value = this.selectData.city;
      this.areaList[2].value = this.selectData.area;
      this.$u.api.getArea().then((res) => {
        if (res.code == 1) {
          this.areaList[0].list = res.data;
        }
      });
      this.$u.api
        .getArea({
          province: this.selectData.province,
        })
        .then((res) => {
          if (res.code == 1) {
            this.areaList[1].list = res.data;
          }
        });
      this.$u.api
        .getArea({
          province: this.selectData.province,
          city: this.selectData.city,
        })
        .then((res) => {
          if (res.code == 1) {
            this.areaList[2].list = res.data;
          }
        });
      // getArea({
      //   params: {
      //     pid: 0,
      //   },
      //   custom: { auth: true },
      // }).then((res) => {
      //   this.areaList[0].list = res
      // })
      // getArea({
      //   params: {
      //     pid: this.selectData.province,
      //   },
      //   custom: { auth: true },
      // }).then((res) => {
      //   this.areaList[1].list = res
      // })
      // getArea({
      //   params: {
      //     pid: this.selectData.city,
      //   },
      //   custom: { auth: true },
      // }).then((res) => {
      //   this.areaList[2].list = res
      // })
    },
    // 获取省区列表
    onGetArea(id) {
      let params;
      switch (this.current) {
        case 1:
          params = {
            "row[province]": id,
          };
          break;
        case 2:
          params = {
            "row[province]": id,
            "row[city]": id,
          };
          break;
        default:
          params = {};
          break;
      }
      this.$u.api.getArea(params).then((res) => {
        if (res.code == 1) {
          this.areaList[this.current].list = res.data;
        }
      });
    },
    // 选择区域
    onSelect(val, idx) {
      let obj = {
        name: "请选择",
      };
      if (
        this.areaList[this.current].value != "" &&
        this.areaList[this.current].value != val.value
      ) {
        // 前面已选地区更换 删除后方已选的数据
        this.tabList.splice(
          this.current,
          this.tabList.length - (this.current + 1)
        );
      }
      // 赋值
      this.tabList[this.current].name = val.name;
      this.areaList[this.current].value = val.value;
      // 赋值操作
      if (idx < this.areaLength) {
        // 添加一个默认值
        if (this.tabList.length != this.areaLength) {
          this.tabList.push(obj);
        }
        if (idx + 1 != this.areaLength) {
          // 切换下一个区域选择
          this.current++;
          // 请求获取
          this.onGetArea(val.value);
        }
      }
      // 最后一个区域选择，关闭弹窗并且传值给父组件
      if (idx == this.areaLength - 1) {
        this.selectValue = false;
        this.$emit("input", this.specShow);
        // 已选择完
        this.onConfirm();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  display: flex;
  flex-direction: column;
  height: 80vh;
  width: 100%;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  position: relative;
  .top-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 30rpx;
    font-size: 32rpx;
    font-weight: bold;
    height: 45px;
  }
  .swiper-block {
    flex: 1;
    .swiper-list {
      height: 100%;
      display: flex;
      flex-direction: column;
      .area-block {
        padding: 18px 15px 0;
        .area-item {
          display: flex;
          align-items: center;
          padding-bottom: 18px;
          .name {
            flex: 1;
            font-size: 15px;
          }
        }
      }
    }
  }
}
</style>
